Work summary
Codes are available at
Boston dataset contains information collected by the U.S Census Service concerning housing valuesin the area of Boston Mass. It was obtained from the StatLib archive. More information about each variable can be found in here
Descriptions of variables are: - CRIM: Per capita crime rate by town - ZN Proportion of residential land zoned for lots over 25,000 sq. ft - INDUS: Proportion of non-retail business acres per town - CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX: Nitric oxide concentration (parts per 10 million) - RM: Average number of rooms per dwelling - AGE: Proportion of owner-occupied units built prior to 1940 - DIS: Weighted distances to five Boston employment centers - RAD: Index of accessibility to radial highways - TAX: Full-value property tax rate per $10,000 - PTRATIO: Pupil-teacher ratio by town - B: 1000(Bk — 0.63)², where Bk is the proportion of [people of African American descent] by town - LSTAT: Percentage of lower status of the population - MEDV: Median value of owner-occupied homes in $1000s
library(MASS)
data("Boston")
dim(Boston)
## [1] 506 14
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
According to the information the Boston data frame has 506 rows and 14 columns. That is equal to my check. There is no missing values either.
sum(is.na(Boston))
## [1] 0
mean(is.na(Boston))
## [1] 0
From graphical overview it is easy to notice at least the following: - rm & medv, nox & indus, age & nox, tax & indus have positive correlation - dis & indus, dis & nox, dis & age, lstat & medv have negative correation - medv and rm seem to fit linear distribution - age and black are left-tailed - crim, dis are right-tailed - tax, rad and indus are bimodally distributed - lstat, nox and dis are skewed to the left
library(GGally)
library(ggplot2)
ggpairs(Boston, mapping = aes(), title="Scatter plot matrix, distributions ",lower = list(combo = wrap("facethist", bins = 20)))
Alt text
pairs(Boston[-1], main="Graphical summary")
Scaling targets to normalising:
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
When summary of scaled data is compared to the original data, it is easy to see that magnitudes of min and max values have decreased and mean is always 0. For instance, max of lstat was 37.97 and after scaling 3.54, respectively black max 396.9 and 0.44. Zn min was 0, now -0.49, rm min was 3.56, now -3.88.
Categorial variable crim is created:
# change the object to data frame, because vector otherwise causes an error in next phase
boston_scaled<-as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
Testing and training sets are created:
# number of rows in the Boston dataset
n <- nrow(boston_scaled)
# randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# creating train set
train <- boston_scaled[ind,]
# create testing set
test <- boston_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
lda.fit <- lda(crime~., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2425743 0.2400990 0.2599010 0.2574257
##
## Group means:
## zn indus chas nox rm
## low 1.07099371 -0.9793247 -0.15180559 -0.8983009 0.50716839
## med_low -0.05692171 -0.4032096 -0.02879709 -0.6033220 -0.08786788
## med_high -0.38841860 0.2037910 0.29011382 0.4035470 0.09292318
## high -0.48724019 1.0170690 -0.08304540 1.0729745 -0.41133267
## age dis rad tax ptratio
## low -0.9415831 0.9684377 -0.6900668 -0.7386637 -0.46634671
## med_low -0.4354850 0.3867381 -0.5437961 -0.5306429 -0.08041325
## med_high 0.4535193 -0.4089745 -0.4404510 -0.3276882 -0.30895324
## high 0.8240565 -0.8732767 1.6386213 1.5144083 0.78135074
## black lstat medv
## low 0.37651322 -0.79870107 0.59400350
## med_low 0.32125190 -0.22603000 0.06581833
## med_high 0.07292401 0.01789565 0.16190949
## high -0.85103145 0.89288792 -0.65343714
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.08892116 0.5489677834 -0.97069282
## indus 0.09491791 -0.3392566678 0.27989828
## chas -0.08890336 -0.1232155443 0.05465976
## nox 0.31622117 -0.5653042497 -1.33259374
## rm -0.10833437 -0.0770258993 -0.22868492
## age 0.22227598 -0.3922525754 -0.22691798
## dis -0.07399109 -0.0517942769 0.02907436
## rad 3.26369193 1.0130398163 0.15650736
## tax 0.12335424 -0.0009651042 0.33312930
## ptratio 0.09706172 0.0342082440 -0.30841673
## black -0.11827530 0.0415207333 0.16331145
## lstat 0.23514733 -0.1126063895 0.22470817
## medv 0.18309423 -0.2162940912 -0.22062650
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9491 0.0401 0.0108
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit, myscale = 1)
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 12 15 2 0
## med_low 2 16 11 0
## med_high 1 5 13 2
## high 0 0 0 23
6. Save the crime categories from the test set and then remove the categorical crime variable from the test dataset. Then predict the classes with the LDA model on the test data. Cross tabulate the results with the crime categories from the test set. Comment on the results. (0-3 points)
Boston dataset is reloaded again and the done modifications are not valid any more. Data is standardi
library(MASS)
data("Boston")
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled2)
## [1] "matrix"
boston_scaled2<-as.data.frame(boston_scaled2)
Distances calculation:
dist_eu<- dist(boston_scaled2)
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
Kmeans clustering and pairs are calculated, but the number of centers here is 4, which is just a guess what could be the optimal number.
km <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2, col = km$cluster)
To find the optimal number of clusters is not irrelevant question and the textbook recommends the method to plot within-group sum of squares associated with the k-means solution for each number of groups. Then the “elbow” in the picture gives indication of the most useful solution. The plot below indicates that the elbow is in 2, after 2 the decrease is slower. However, even with 3 it is still significant but I choose to use 2.
set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line', main="WGSS and groups in K-means solution")
Only 51 % total variance in data set that is explained by the first clustering with 4 clusters, which is not impressive. I checked how many clusters I should have to gain 80 % of total variance and it was 20. It is clear that it is too much, so I still keep 2 clusters, although the biggest decrease of variation ends at 2. In real-life I should check the correct number of clusters also by other methods, e.g. silhouette.
str(km)
## List of 9
## $ cluster : Named int [1:506] 2 2 2 4 4 2 2 2 2 2 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:4, 1:14] 0.386 -0.377 1.917 -0.408 -0.487 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:4] "1" "2" "3" "4"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:4] 1007 1320 395 759
## $ tot.withinss: num 3481
## $ betweenss : num 3589
## $ size : int [1:4] 128 230 42 106
## $ iter : int 4
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
km
## K-means clustering with 4 clusters of sizes 128, 230, 42, 106
##
## Cluster means:
## crim zn indus chas nox rm
## 1 0.3860352 -0.4872402 1.1771014 0.09677408 1.1367747 -0.46615004
## 2 -0.3770079 -0.3379159 -0.3487836 0.01867399 -0.3649600 -0.09114314
## 3 1.9167567 -0.4872402 1.0201311 -0.27232907 1.0484799 -0.41225609
## 4 -0.4075892 1.5146367 -1.0688137 -0.04947434 -0.9962503 0.92400834
## age dis rad tax ptratio black
## 1 0.81134294 -0.8414722 1.0055151 1.1534294 0.5524522 0.1238290
## 2 -0.05757083 0.0803019 -0.5774111 -0.6094786 -0.1007611 0.2875071
## 3 0.78947129 -0.8908848 1.6076484 1.4922585 0.7452908 -2.8449572
## 4 -1.16762641 1.1948695 -0.5983266 -0.6616391 -0.7437834 0.3538816
## lstat medv
## 1 0.7316707 -0.52309197
## 2 -0.1970688 0.04479413
## 3 1.2421501 -1.12167260
## 4 -0.9480974 0.97889973
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 2 2 2 4 4 2 2 2 2 2 2 2 2 2 2 2 2 2
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 2 2 2 4 4 4 2 2 2 2 2 2 2 2 2 2 4 4
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 4 4 4 4 4 2 2 2 2 4 4 4 4 2 2 2 2 2
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 2 2 2 2 2 2 2 2 4 2 4 2 2 2 2 2 2 2
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 2 2 2 2 2 2 2 4 4 2 2 2 2 2 2 2 2 2
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 1 1 1 1 1 1 1 1 1 1 1 1 3 2 2 1 2 2
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 2 2 2 2 2 2 4 4 4 4 4 4 4 4 4 4 4 4
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 4 4 4 4 4 4 4 2 2 2 2 2 2 2 2 2 2 2
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 2 2 2 2 2 2 2 2 4 4 2 2 4 2 2 2 4 4
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 2 2 2 2 4 4 4 2 4 4 2 2 4 2 4 4 4 4
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 4 4 4 4 4 4 2 2 2 4 4 2 2 2 2 4 4 2
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 2 2 2 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 4 4 4 4 4 2 2 2 2 2 4 4 4 4 4 4 4 2
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 2 2 2 2 2 2 2 4 4 2 2 2 2 2 2 2 2 4
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 2 4 4 2 2 4 4 4 4 4 4 4 4 4 1 1 1 1
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 1 1 3 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 1 1 3 1 1 1 1 1 3 3 1 1 1 3 3 3 3 3
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 3 3 3 3 3 3 1 1 1 3 3 3 3 3 3 3 3 3
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 3 3 3 3 3 3 3 1 1 1 1 1 3 3 1 1 1 1
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 3 1 1 1 3 3 3 3 1 1 1 1 1 1 1 1 3 1
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
## 505 506
## 2 2
##
## Within cluster sum of squares by cluster:
## [1] 1006.8229 1320.4460 395.1207 758.7999
## (between_SS / total_SS = 50.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
The plot picture shows the groups are not equal size, one is 177 and other 329. There are some pairs, in which the grouping seems to work nicely; for instance medvd & lstat, lstat & nox,dis & nox and rm & nox. But for some pairs the groups are unclear, for instance rm&ptratio, age & ptratio, ptratio & lstat.
km <-kmeans(boston_scaled2, centers = 2)
pairs(boston_scaled2, col = km$cluster)
km <-kmeans(boston_scaled2, centers = 2)
str(km)
## List of 9
## $ cluster : Named int [1:506] 2 2 2 2 2 2 2 2 2 2 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:2, 1:14] 0.724 -0.389 -0.487 0.262 1.143 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:2] "1" "2"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:2] 1891 2686
## $ tot.withinss: num 4577
## $ betweenss : num 2493
## $ size : int [1:2] 177 329
## $ iter : int 1
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
Start again with data reloading and scaling
library(MASS)
library(ggplot2)
library(tidyr)
library(cluster)
data("Boston")
boston_scaled3 <- scale(Boston)
boston_scaled3<-as.data.frame(boston_scaled3)
Number of clusters is selected to be 5 and clusters are target classess.
km_4 <-kmeans(boston_scaled3, centers = 5)
lda.fit2 <- lda(km_4$cluster ~., data = boston_scaled3)
lda.fit2
## Call:
## lda(km_4$cluster ~ ., data = boston_scaled3)
##
## Prior probabilities of groups:
## 1 2 3 4 5
## 0.25296443 0.21146245 0.31027668 0.09881423 0.12648221
##
## Group means:
## crim zn indus chas nox rm
## 1 1.0878724 -0.4872402 1.0149946 -0.1492947 1.0187219 -0.4210063
## 2 -0.3243708 -0.4822312 0.6185681 0.1324196 0.4947716 -0.5346882
## 3 -0.3981592 -0.1664810 -0.6090235 -0.2221749 -0.6655615 -0.1199301
## 4 -0.3103881 -0.1159242 -0.4991257 1.0662850 -0.0692028 1.6606848
## 5 -0.4142124 2.2796750 -1.1802049 -0.2108119 -1.1778698 0.7327381
## age dis rad tax ptratio black
## 1 0.7521154 -0.8135370 1.6596029 1.5294129 0.8057784 -0.7784115
## 2 0.7503783 -0.5640394 -0.5954711 -0.1985406 0.1042866 0.0419631
## 3 -0.6336330 0.5362710 -0.5817365 -0.7039306 -0.0756665 0.3655348
## 4 0.2630692 -0.4217934 -0.3042757 -0.5487050 -0.9864145 0.3028535
## 5 -1.4099114 1.5840638 -0.6588648 -0.5713854 -0.8296553 0.3533591
## lstat medv
## 1 0.8914421 -0.75669132
## 2 0.5669361 -0.49061591
## 3 -0.4149421 0.05516096
## 4 -0.9553010 1.76459824
## 5 -0.9664968 0.81972201
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3 LD4
## crim -0.053751141 0.179074873 0.13780108 -0.07519738
## zn 0.062843967 1.465907935 -0.50908589 1.32076958
## indus -0.179836757 -0.391770295 -0.40486479 0.39138090
## chas 0.230845551 -0.111364285 0.41752818 0.17516588
## nox 0.076978215 -0.081264681 -0.04255968 0.44218751
## rm -0.111320904 0.164332062 0.59726088 0.22808090
## age -0.048463133 -0.522072143 0.34421689 0.63414099
## dis 0.291886353 0.306401440 -0.21018069 -0.27013447
## rad -4.160201638 1.135383393 0.44562029 -1.62967439
## tax 0.204066630 0.381083248 -0.11925476 1.00108406
## ptratio 0.009872979 -0.170859777 -0.22250511 0.33481849
## black 0.025657288 0.005723222 -0.01480980 -0.08944504
## lstat -0.105055816 -0.045731798 0.14150418 0.39609928
## medv 0.351343258 0.268482029 0.88984740 0.30142226
##
## Proportion of trace:
## LD1 LD2 LD3 LD4
## 0.7423 0.1680 0.0517 0.0381
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
Biplot drawing next:
plot(lda.fit2, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit2, myscale = 1)
Samples are displayed as points while variables are displayed either as vectors, linear axes or nonlinear trajectories. In the case of categorical variables, category level points may be used to represent the levels of a categorical variable.
Arrows for each variable point in the direction of increasing values of that variable.Rad increases meaning higher the value, the more meaningful it is in clustering. Indus points down indicating it decreases. Also Zn points out, but otherwise all variables are around zero meaning they are not influencial
I copied the lines from the instructions and did the package installation
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
Then I tried plotting as instucted
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
However, at this point I run into trouble with WebGL. In the help page the cube is rolling but I just did not succeed in R Studio.
hd <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human_development.csv", stringsAsFactors = F)
gii <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/gender_inequality.csv", stringsAsFactors = F, na.strings = "..")
#checking the dimension
dim(hd)
## [1] 195 8
dim(gii)
## [1] 195 10
#checking the structure
str(hd)
## 'data.frame': 195 obs. of 8 variables:
## $ HDI.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Human.Development.Index..HDI. : num 0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
## $ Life.Expectancy.at.Birth : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Expected.Years.of.Education : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Mean.Years.of.Education : num 12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
## $ Gross.National.Income..GNI..per.Capita: chr "64,992" "42,261" "56,431" "44,025" ...
## $ GNI.per.Capita.Rank.Minus.HDI.Rank : int 5 17 6 11 9 11 16 3 11 23 ...
str(gii)
## 'data.frame': 195 obs. of 10 variables:
## $ GII.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Gender.Inequality.Index..GII. : num 0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
## $ Maternal.Mortality.Ratio : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Adolescent.Birth.Rate : num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Percent.Representation.in.Parliament : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
## $ Population.with.Secondary.Education..Female.: num 97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
## $ Population.with.Secondary.Education..Male. : num 96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
## $ Labour.Force.Participation.Rate..Female. : num 61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
## $ Labour.Force.Participation.Rate..Male. : num 68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
summary(hd)
## HDI.Rank Country Human.Development.Index..HDI.
## Min. : 1.00 Length:195 Min. :0.3480
## 1st Qu.: 47.75 Class :character 1st Qu.:0.5770
## Median : 94.00 Mode :character Median :0.7210
## Mean : 94.31 Mean :0.6918
## 3rd Qu.:141.25 3rd Qu.:0.8000
## Max. :188.00 Max. :0.9440
## NA's :7
## Life.Expectancy.at.Birth Expected.Years.of.Education
## Min. :49.00 Min. : 4.10
## 1st Qu.:65.75 1st Qu.:11.10
## Median :73.10 Median :13.10
## Mean :71.07 Mean :12.86
## 3rd Qu.:76.80 3rd Qu.:14.90
## Max. :84.00 Max. :20.20
##
## Mean.Years.of.Education Gross.National.Income..GNI..per.Capita
## Min. : 1.400 Length:195
## 1st Qu.: 5.550 Class :character
## Median : 8.400 Mode :character
## Mean : 8.079
## 3rd Qu.:10.600
## Max. :13.100
##
## GNI.per.Capita.Rank.Minus.HDI.Rank
## Min. :-84.0000
## 1st Qu.: -9.0000
## Median : 1.5000
## Mean : 0.1862
## 3rd Qu.: 11.0000
## Max. : 47.0000
## NA's :7
summary(gii)
## GII.Rank Country Gender.Inequality.Index..GII.
## Min. : 1.00 Length:195 Min. :0.0160
## 1st Qu.: 47.75 Class :character 1st Qu.:0.2030
## Median : 94.00 Mode :character Median :0.3935
## Mean : 94.31 Mean :0.3695
## 3rd Qu.:141.25 3rd Qu.:0.5272
## Max. :188.00 Max. :0.7440
## NA's :7 NA's :33
## Maternal.Mortality.Ratio Adolescent.Birth.Rate
## Min. : 1.0 Min. : 0.60
## 1st Qu.: 16.0 1st Qu.: 15.45
## Median : 69.0 Median : 40.95
## Mean : 163.2 Mean : 49.55
## 3rd Qu.: 230.0 3rd Qu.: 71.78
## Max. :1100.0 Max. :204.80
## NA's :10 NA's :5
## Percent.Representation.in.Parliament
## Min. : 0.00
## 1st Qu.:12.47
## Median :19.50
## Mean :20.60
## 3rd Qu.:27.02
## Max. :57.50
## NA's :3
## Population.with.Secondary.Education..Female.
## Min. : 0.9
## 1st Qu.: 27.8
## Median : 55.7
## Mean : 54.8
## 3rd Qu.: 81.8
## Max. :100.0
## NA's :26
## Population.with.Secondary.Education..Male.
## Min. : 3.20
## 1st Qu.: 38.30
## Median : 60.00
## Mean : 60.29
## 3rd Qu.: 85.80
## Max. :100.00
## NA's :26
## Labour.Force.Participation.Rate..Female.
## Min. :13.50
## 1st Qu.:44.50
## Median :53.30
## Mean :52.61
## 3rd Qu.:62.62
## Max. :88.10
## NA's :11
## Labour.Force.Participation.Rate..Male.
## Min. :44.20
## 1st Qu.:68.88
## Median :75.55
## Mean :74.74
## 3rd Qu.:80.15
## Max. :95.50
## NA's :11
Renaming the columns:
names(hd)[names(hd) == "Human.Development.Index..HDI."] <- "HDI"
names(hd)[names(hd) == "Expected.Years.of.Education"] <- "EYE"
names(hd)[names(hd) == "Life.Expectancy.at.Birth"] <- "LEB"
names(hd)[names(hd) == "Mean.Years.of.Education"] <- "MYE"
names(hd)[names(hd) == "Gender.Inequality.Index..GII."] <- "GII"
names(hd)[names(hd) == "Maternal.Mortality.Ratio"] <- "MMR"
names(hd)[names(hd) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(hd)[names(hd) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(hd)[names(hd) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(hd)[names(hd) == "GNI.per.Capita.Rank.Minus.HDI.Rank"] <- "GNIMinusHDIRank"
names(gii)[names(gii) == "Adolescent.Birth.Rate"] <- "ADBR"
names(gii)[names(gii) == "Expected.Years.of.Education"] <- "EYE"
names(gii)[names(gii) == “Life.Expectancy.at.Birth”] <- “LEB” names(gii)[names(gii) == “Mean.Years.of.Education”] <- “MYE” names(gii)[names(gii) == “Gender.Inequality.Index..GII.”] <- “GII” names(gii)[names(gii) == “Maternal.Mortality.Ratio”] <- “MMR” names(gii)[names(gii) == “Percent.Representation.in.Parliament”] <- “PerParliament” names(gii)[names(gii) == “Population.with.Secondary.Education..Male.”] <- “SecEducMale” names(gii)[names(gii) == “Population.with.Secondary.Education..Female.”] <- “SecEducFemal” names(gii)[names(gii) == “Gross.National.Income..GNI..per.Capita”] <- “GNIncPerCap” names(gii)[names(gii) == “Labour.Force.Participation.Rate..Female.”] <- “LabForParFem” names(gii)[names(gii) == “Labour.Force.Participation.Rate..Male.”] <- “LabForParMale” head(hd) head(gii)